package org.tigris.atlas.examples.service.impl;

import java.util.Collection;

import org.tigris.atlas.examples.bizobj.TxnTestDomainAssembler;
import org.tigris.atlas.examples.bizobj.TxnTestDomainBO;
import org.tigris.atlas.examples.service.EntityMaintenanceService;
import org.tigris.atlas.examples.service.ServiceFactory;
import org.tigris.atlas.examples.service.TxnTestDomainCollectionServiceResponse;
import org.tigris.atlas.examples.service.TxnTestDomainServiceResponse;
import org.tigris.atlas.service.VoidServiceResponse;

import org.tigris.atlas.examples.transfer.TransferObjectFactory;
import org.tigris.atlas.examples.transfer.TxnTestDomain;

/**
 * Service implementation class for the TxnTest service
 * @see org.tigris.atlas.examples.service.TxnTestService
 */
public class TxnTestServiceImpl extends TxnTestServiceBaseImpl {

	/**
	 * Execute the CreateOneFailOne service
	 * @see org.tigris.atlas.examples.service.TxnTestService#CreateOneFailOne()
	 */
	protected void createOneFailOneImpl(VoidServiceResponse response) {
		TxnTestDomain domain1 = TransferObjectFactory.createTxnTestDomain();
		domain1.setName("Name1");
		saveDomain(domain1, false);
		
		TxnTestDomain domain2 = TransferObjectFactory.createTxnTestDomain();
		// Don't set the name to ensure error
		//domain2.setName("Name2");
		saveDomain(domain2, true);
	}


	/**
	 * Execute the SelectAllRecords service
	 * @see org.tigris.atlas.examples.service.TxnTestService#SelectAllRecords()
	 */
	protected void selectAllRecordsImpl(TxnTestDomainCollectionServiceResponse response) {
		Collection bos = TxnTestDomainBO.selectAllTxnTestDomains();
		Collection tos = TxnTestDomainAssembler.getTxnTestDomainCollection(bos);
		response.addTxnTestDomains(tos);
	}


	/**
	 * Execute the CreateTwo service
	 * @see org.tigris.atlas.examples.service.TxnTestService#CreateTwo()
	 */
	protected void createTwoImpl(VoidServiceResponse response) {
		TxnTestDomain domain1 = TransferObjectFactory.createTxnTestDomain();
		domain1.setName("Name1");
		saveDomain(domain1, false);
		
		TxnTestDomain domain2 = TransferObjectFactory.createTxnTestDomain();
		domain2.setName("Name2");
		saveDomain(domain2, false);
	}


	private void saveDomain(TxnTestDomain domain, boolean errorsExpected) {
		EntityMaintenanceService delegate = ServiceFactory.createEntityMaintenanceService();
		TxnTestDomainServiceResponse response = delegate.save(domain);
		domain = response.getTxnTestDomain();
		
		if (domain.getMessages().hasErrorMessages() && !errorsExpected) {
			throw new RuntimeException("Received unexpected errors");
		} else if (!domain.getMessages().hasErrorMessages() && errorsExpected) {
			throw new RuntimeException("Expected errors but received none");
		}
	}
}